/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.PreexistingEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.entity.Restaurant;
import model.entity.OrderDetail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import model.entity.Items;

/**
 *
 * @author lnngu_000
 */
public class ItemsJpaController implements Serializable {

    public ItemsJpaController(EntityManagerFactory emf) {
       
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Items items) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (items.getOrderDetailCollection() == null) {
            items.setOrderDetailCollection(new ArrayList<OrderDetail>());
        }
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Restaurant restaurantId = items.getRestaurantId();
            if (restaurantId != null) {
                restaurantId = em.getReference(restaurantId.getClass(), restaurantId.getRestaurantId());
                items.setRestaurantId(restaurantId);
            }
            Collection<OrderDetail> attachedOrderDetailCollection = new ArrayList<OrderDetail>();
            for (OrderDetail orderDetailCollectionOrderDetailToAttach : items.getOrderDetailCollection()) {
                orderDetailCollectionOrderDetailToAttach = em.getReference(orderDetailCollectionOrderDetailToAttach.getClass(), orderDetailCollectionOrderDetailToAttach.getOrderDetailId());
                attachedOrderDetailCollection.add(orderDetailCollectionOrderDetailToAttach);
            }
            items.setOrderDetailCollection(attachedOrderDetailCollection);
            em.persist(items);
            if (restaurantId != null) {
                restaurantId.getItemsCollection().add(items);
                restaurantId = em.merge(restaurantId);
            }
            for (OrderDetail orderDetailCollectionOrderDetail : items.getOrderDetailCollection()) {
                Items oldItemIdOfOrderDetailCollectionOrderDetail = orderDetailCollectionOrderDetail.getItemId();
                orderDetailCollectionOrderDetail.setItemId(items);
                orderDetailCollectionOrderDetail = em.merge(orderDetailCollectionOrderDetail);
                if (oldItemIdOfOrderDetailCollectionOrderDetail != null) {
                    oldItemIdOfOrderDetailCollectionOrderDetail.getOrderDetailCollection().remove(orderDetailCollectionOrderDetail);
                    oldItemIdOfOrderDetailCollectionOrderDetail = em.merge(oldItemIdOfOrderDetailCollectionOrderDetail);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findItems(items.getItemId()) != null) {
                throw new PreexistingEntityException("Items " + items + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Items items) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Items persistentItems = em.find(Items.class, items.getItemId());
            Restaurant restaurantIdOld = persistentItems.getRestaurantId();
            Restaurant restaurantIdNew = items.getRestaurantId();
            Collection<OrderDetail> orderDetailCollectionOld = persistentItems.getOrderDetailCollection();
            Collection<OrderDetail> orderDetailCollectionNew = items.getOrderDetailCollection();
            if (restaurantIdNew != null) {
                restaurantIdNew = em.getReference(restaurantIdNew.getClass(), restaurantIdNew.getRestaurantId());
                items.setRestaurantId(restaurantIdNew);
            }
            Collection<OrderDetail> attachedOrderDetailCollectionNew = new ArrayList<OrderDetail>();
            for (OrderDetail orderDetailCollectionNewOrderDetailToAttach : orderDetailCollectionNew) {
                orderDetailCollectionNewOrderDetailToAttach = em.getReference(orderDetailCollectionNewOrderDetailToAttach.getClass(), orderDetailCollectionNewOrderDetailToAttach.getOrderDetailId());
                attachedOrderDetailCollectionNew.add(orderDetailCollectionNewOrderDetailToAttach);
            }
            orderDetailCollectionNew = attachedOrderDetailCollectionNew;
            items.setOrderDetailCollection(orderDetailCollectionNew);
            items = em.merge(items);
            if (restaurantIdOld != null && !restaurantIdOld.equals(restaurantIdNew)) {
                restaurantIdOld.getItemsCollection().remove(items);
                restaurantIdOld = em.merge(restaurantIdOld);
            }
            if (restaurantIdNew != null && !restaurantIdNew.equals(restaurantIdOld)) {
                restaurantIdNew.getItemsCollection().add(items);
                restaurantIdNew = em.merge(restaurantIdNew);
            }
            for (OrderDetail orderDetailCollectionOldOrderDetail : orderDetailCollectionOld) {
                if (!orderDetailCollectionNew.contains(orderDetailCollectionOldOrderDetail)) {
                    orderDetailCollectionOldOrderDetail.setItemId(null);
                    orderDetailCollectionOldOrderDetail = em.merge(orderDetailCollectionOldOrderDetail);
                }
            }
            for (OrderDetail orderDetailCollectionNewOrderDetail : orderDetailCollectionNew) {
                if (!orderDetailCollectionOld.contains(orderDetailCollectionNewOrderDetail)) {
                    Items oldItemIdOfOrderDetailCollectionNewOrderDetail = orderDetailCollectionNewOrderDetail.getItemId();
                    orderDetailCollectionNewOrderDetail.setItemId(items);
                    orderDetailCollectionNewOrderDetail = em.merge(orderDetailCollectionNewOrderDetail);
                    if (oldItemIdOfOrderDetailCollectionNewOrderDetail != null && !oldItemIdOfOrderDetailCollectionNewOrderDetail.equals(items)) {
                        oldItemIdOfOrderDetailCollectionNewOrderDetail.getOrderDetailCollection().remove(orderDetailCollectionNewOrderDetail);
                        oldItemIdOfOrderDetailCollectionNewOrderDetail = em.merge(oldItemIdOfOrderDetailCollectionNewOrderDetail);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = items.getItemId();
                if (findItems(id) == null) {
                    throw new NonexistentEntityException("The items with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            Items items;
            em.getTransaction().begin();
            try {
                items = em.getReference(Items.class, id);
                items.getItemId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The items with id " + id + " no longer exists.", enfe);
            }
            Restaurant restaurantId = items.getRestaurantId();
            if (restaurantId != null) {
                restaurantId.getItemsCollection().remove(items);
                restaurantId = em.merge(restaurantId);
            }
            Collection<OrderDetail> orderDetailCollection = items.getOrderDetailCollection();
            for (OrderDetail orderDetailCollectionOrderDetail : orderDetailCollection) {
                orderDetailCollectionOrderDetail.setItemId(null);
                orderDetailCollectionOrderDetail = em.merge(orderDetailCollectionOrderDetail);
            }
            em.remove(items);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Items> findItemsEntities() {
        return findItemsEntities(true, -1, -1);
    }

    public List<Items> findItemsEntities(int maxResults, int firstResult) {
        return findItemsEntities(false, maxResults, firstResult);
    }

    private List<Items> findItemsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Items.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Items findItems(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Items.class, id);
        } finally {
            em.close();
        }
    }

    public int getItemsCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Items> rt = cq.from(Items.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
